package com.yh.csx.event.store.gateway.backup;

import com.yh.csx.bsf.core.util.NetworkUtils;
import com.yh.csx.bsf.redis.RedisProvider;
import com.yh.csx.bsf.redis.impl.RedisLock;
import com.yh.csx.event.client.thread.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.yh.csx.event.client.Constants.YYYY_MM_DD_00_00_00;

/**
 * @author zhangsheng
 * @date 2021/8/24 17:47
 */
@Slf4j
@Component
public class BackupEventGateway {
    public static final String CSX_B_2_B_EVENT_BACK_UP_EVENT = "csx_b2b_event_back_up_event";
    @Value("${bsf.event.backup.timer.delay.seconds:3600}")
    private int timerDelaySeconds = 60 * 60;
    @Value("${bsf.event.backup.before.days:2}")
    private int beforeDays;
    @Autowired
    private EventResultBakRepository eventResultBakRepository;
    @Autowired
    private EventBakRepository eventBakRepository;
    private ScheduledExecutorService timer;

    @Autowired
    private RedisProvider redisProvider;

    @PostConstruct
    public void init() {
        log.info("=bakUpData=>");
        timer = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("backupData", true));
        timer.scheduleWithFixedDelay(() -> bakUpData(), 10, timerDelaySeconds, TimeUnit.SECONDS);
    }

    private void bakUpData() {
        try {
            redisProvider.tryLock(CSX_B_2_B_EVENT_BACK_UP_EVENT, 60 * 60, () -> {
                log.info("=bakUpData=>");
                eventResultBakRepository.move2Temp(DateFormatUtils.format(DateUtils.addDays(new Date(), -beforeDays), YYYY_MM_DD_00_00_00));
                eventResultBakRepository.move2Bak();
                eventBakRepository.move2Bak();
                eventResultBakRepository.delResult();
                eventBakRepository.delEvent();
                eventResultBakRepository.delTemp();
            });
        } catch (Exception e) {
            log.error("=bakUpData=> error :", e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (null != timer) {
            timer.shutdown();
        }
    }
}
